<template>
  <div class="app-container">
    <!-- 标签切换 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="正常结果" name="normal"></el-tab-pane>
      <el-tab-pane label="异常结果" name="abnormal"></el-tab-pane>
    </el-tabs>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
       <el-form-item label="国家机构编码" prop="fixmedinsCode">
        <el-input
          v-model="queryParams.fixmedinsCode"
          placeholder="请输入国家机构编码"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="信息系统院ID" prop="systemId">
        <el-input
          v-model="queryParams.systemId"
          placeholder="请输入信息系统院ID"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检查唯一标识符" prop="risStudyId">
        <el-input
          v-model="queryParams.risStudyId"
          placeholder="请输入检查唯一标识符"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上报节点" prop="source"  v-if="showSourceSelect">
  <el-select
    v-model="queryParams.source"
    placeholder="请选择上报节点"
    clearable
    style="width: 200px"
  >
    <el-option
      v-for="item in api_load_type"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
</el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="tipList">
      <el-table-column label="国家机构编码" align="center" prop="fixmedinsCode" />
      <el-table-column label="信息系统院内唯一ID" align="center" prop="systemId" />
      <el-table-column label="检查唯一标识符" align="center" prop="risStudyId" />

      <!-- API字段列，带状态标识 -->
      <el-table-column
        v-for="field in apiFields"
        :key="field.prop"
        :label="field.label"
        align="center"
        :prop="field.prop"
      >
        <template #default="scope">
          <div class="api-field-cell" @click="handleFieldClick(scope.row, field)">
            <span v-if="scope.row[field.prop]">
              <el-icon class="abnormal-icon" title="有异常"><Warning /></el-icon>
              <span class="abnormal-text">异常</span>
            </span>
            <span v-else class="normal-text">正常</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="上报节点" align="center" prop="source">
        <template #default="scope">
          <dict-tag :options="api_load_type" :value="scope.row.source" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'danger' : 'success'">
            {{ scope.row.status === 1 ? '异常' : '正常' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 多列数据弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="80%"
      :before-close="handleDialogClose"
    >
      <el-table :data="dialogTableData" v-loading="dialogLoading" style="width: 100%">
        <el-table-column
          v-for="column in dialogColumns"
          :key="column.prop"
          :label="column.label"
          :prop="column.prop"
          :width="column.width"
          :show-overflow-tooltip="true"
        />
      </el-table>
    </el-dialog>

    <!-- 单列数据弹窗 -->
    <el-dialog
      :title="singleColumnDialogTitle"
      v-model="singleColumnDialogVisible"
      width="60%"
      :before-close="handleSingleColumnDialogClose"
    >
      <div v-if="exceptionDetailList.length">
        <div v-for="item in exceptionDetailList" :key="item.source" class="exception-group">
          <div class="group-title">{{ sourceLabel(item.source) }}</div>
          <div class="group-msg">
            <div v-for="msg in item.msgList" :key="msg" class="msg-line">
              <el-icon style="color: var(--el-color-danger);margin-right:4px;"><Warning /></el-icon>{{ msg }}
            </div>
          </div>
          <div class="group-time">更新时间：{{ item.updateTime }}</div>
        </div>
      </div>
      <div v-else class="single-column-dialog-content">
        <div class="single-column-content">{{ singleColumnContent }}</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Warning, Search, Refresh } from '@element-plus/icons-vue'
import { listTip, getExceptionDetail } from "@/api/os/tip"
import useUserStore from '@/store/modules/user'
import { de } from 'element-plus/es/locales.mjs'
const { proxy } = getCurrentInstance()
const { api_load_type } = proxy.useDict("api_load_type")




// 获取用户信息并判断是否显示上报节点
const showSourceSelect = computed(() => {
  // 方法1：从 store 获取
    const userStore = useUserStore()
  const user =userStore.userInfo
  if (user  && user.userType === '01') {
    return true
  }
  return false;
  
})



// API字段配置
const API_FIELDS_CONFIG = {
  apiPatientApply: {
    label: '患者申请信息上传',
    apiType: 'patient_apply',
    columns: [
      { prop: 'psnName', label: '人员姓名', width: 100 },
      { prop: 'psnCertType', label: '证件类型', width: 80 },
      { prop: 'certno', label: '证件号码', width: 120 },
      { prop: 'fixmedinsCode', label: '机构代码', width: 100 },
      { prop: 'examItemCode', label: '检查项目代码', width: 120 },
      { prop: 'imgExamItem', label: '检查项目名称', width: 150 },
      { prop: 'appyNo', label: '申请单号', width: 120 },
      { prop: 'errorMsg', label: '错误信息', width: 200 }
    ]
  },
  apiPatientCheck: {
    label: '患者检查数据上传',
    apiType: 'patient_check',
    columns: [
      { prop: 'psnName', label: '人员姓名', width: 100 },
      { prop: 'examItemCode', label: '检查项目代码', width: 120 },
      { prop: 'imgExamItem', label: '检查项目名称', width: 150 },
      { prop: 'examDate', label: '检查日期', width: 100 },
      { prop: 'studyInstanceUid', label: '检查UID', width: 150 },
      { prop: 'errorMsg', label: '错误信息', width: 200 }
    ]
  },
  apiPatientReport: {
    label: '患者报告数据上传',
    apiType: 'patient_report',
    columns: [
      { prop: 'psnName', label: '人员姓名', width: 100 },
      { prop: 'rpotNo', label: '报告编号', width: 120 },
      { prop: 'rptDate', label: '报告日期', width: 120 },
      { prop: 'examRsltCode', label: '检查结果', width: 100 },
      { prop: 'errorMsg', label: '错误信息', width: 200 }
    ]
  },
  apiReportSnapshot: {
    label: '报告快照PDF上传',
    apiType: 'report_snapshot',
    columns: [
      { prop: 'rpotNo', label: '报告编号', width: 120 },
      { prop: 'snapshotSeriesNumber', label: '快照序号', width: 100 },
      { prop: 'studyInstanceUid', label: '检查UID', width: 150 },
      { prop: 'errorMsg', label: '错误信息', width: 200 }
    ]
  },
  apiImageSequence: {
    label: '影像序列信息上报',
    apiType: 'image_sequence',
    columns: [
      { prop: 'studyInstanceUid', label: '检查UID', width: 150 },
      { prop: 'seriesInstanceUid', label: '序列UID', width: 150 },
      { prop: 'seriesNumber', label: '序列号', width: 80 },
      { prop: 'seriesImageCount', label: '影像数量', width: 80 },
      { prop: 'errorMsg', label: '错误信息', width: 200 }
    ]
  },
  apiImageVideo: {
    label: '影像图像信息上报',
    apiType: 'image_video',
    columns: [
      { prop: 'studyInstanceUid', label: '检查UID', width: 150 },
      { prop: 'seriesInstanceUid', label: '序列UID', width: 150 },
      { prop: 'sopInstanceUid', label: '图像UID', width: 150 },
      { prop: 'keyImageFlag', label: '关键图', width: 80 },
      { prop: 'errorMsg', label: '错误信息', width: 200 }
    ]
  },
  apiSettlement: {
    label: '结算信息上报',
    apiType: 'settlement',
    columns: [
      { prop: 'hospitalSetNo', label: '结算ID', width: 120 },
      { prop: 'psnName', label: '患者姓名', width: 100 },
      { prop: 'setlType', label: '结算类型', width: 80 },
      { prop: 'projMon', label: '总金额', width: 100 },
      { prop: 'errorMsg', label: '错误信息', width: 200 }
    ]
  },
  apiDicomFile: {
    label: 'dicom文件上报',
    apiType: 'invalid_index',
    columns: [
      { prop: 'content', label: '作废内容', width: 300 },
      { prop: 'remark', label: '备注', width: 200 }
    ]
  }
}

// 响应式数据
const activeTab = ref('normal')
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const tipList = ref([])
const apiFields = ref(Object.keys(API_FIELDS_CONFIG).map(key => ({
  prop: key,
  label: API_FIELDS_CONFIG[key].label
})))

// 多列弹窗相关
const dialogVisible = ref(false)
const dialogLoading = ref(false)
const dialogTitle = ref('')
const dialogTableData = ref([])
const dialogColumns = ref([])
const currentField = ref(null)
const currentRow = ref(null)

// 单列弹窗相关
const singleColumnDialogVisible = ref(false)
const singleColumnDialogTitle = ref('')
const singleColumnContent = ref('')
const exceptionDetailList = ref([]) // 新增：分组异常详情

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  fixmedinsCode: null,
  systemId: null,
  risStudyId: null,
  status: null,
  source: null
})

// 监听activeTab变化，自动更新查询
watch(activeTab, (newTab) => {
  queryParams.pageNum = 1
  updateQueryParamsByTab(newTab)
  getList()
})

// 根据标签更新查询参数
const updateQueryParamsByTab = (tab) => {
  if (tab === 'abnormal') {
    queryParams.status = 1 // 异常
    queryParams.source = null // 清除source过滤
  } else if (tab === 'normal') {
    queryParams.status = 0 // 正常
    queryParams.source = null // 只查询最后一步
  }
}

// 方法
const getList = () => {
  loading.value = true

  // 构建POST请求参数
  const params = {
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
    fixmedinsCode: queryParams.fixmedinsCode,
    systemId: queryParams.systemId,
    risStudyId: queryParams.risStudyId,
    source: queryParams.source,
    status: queryParams.status // 确保status参数正确传递
  }

  // 使用POST请求
  listTip(params).then(response => {
    tipList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

const handleTabClick = (tab) => {
  // 这里不需要额外处理，因为watch已经监听了activeTab的变化
}

const handleFieldClick = (row, field) => {
  if (!row[field.prop]) {
    return // 正常字段不处理
  }

  currentRow.value = row
  currentField.value = field
  showSingleColumnData(row[field.prop], `${field.label} - 内容详情`)
}

const showSingleColumnData = (content, title) => {
  singleColumnDialogTitle.value = title
  singleColumnDialogVisible.value = true
  exceptionDetailList.value = [] // 每次弹窗前清空

  if (!content) {
    singleColumnContent.value = '无数据'
    return
  }

  try {
    // 尝试解析JSON
    const data = JSON.parse(content)
    if (typeof data === 'object' && data !== null && !Array.isArray(data)) {
      // 新增：如果是你给的异常json结构，分组美观展示
      exceptionDetailList.value = formatExceptionDetail(data)
      singleColumnContent.value = '' // 清空原内容
      return
    }
  } catch (e) {
    // 非json，走原有逻辑
  }
  // 不是json，走原有逻辑
  exceptionDetailList.value = []
  formatSingleColumnContent(content)
}

// 格式化异常详情为分组数组
function formatExceptionDetail(data) {
  return Object.entries(data).map(([source, info]) => ({
    source,
    msgList: (info.msg || '').split(';').filter(Boolean),
    updateTime: info.updateTime ? formatTime(info.updateTime) : ''
  }))
}

// 时间戳格式化
function formatTime(ts) {
  const date = new Date(ts)
  return date.toLocaleString()
}

// 服务名映射（改为用字典 api_load_type 获取 label）
function sourceLabel(source) {
  // 兼容 api_load_type 为对象或数组
  let dict = api_load_type;
  if (!Array.isArray(dict)) {
    dict = Object.values(dict);
  }
  const found = dict[0].api_load_type.find(item => item.value === source);
  return found ? found.label : source;
}

const formatSingleColumnContent = (content) => {
  // 检查是否是分号分隔的键值对
  if (content.includes(';')) {
    const lines = content.split(';').filter(line => line.trim())
    let formattedContent = ''
    lines.forEach(line => {
      const colonIndex = line.indexOf(':')
      if (colonIndex > 0) {
        const key = line.substring(0, colonIndex).trim()
        const value = line.substring(colonIndex + 1).trim()
        formattedContent += `${key}: ${value}\n`
      } else {
        formattedContent += `${line.trim()}\n`
      }
    })
    singleColumnContent.value = formattedContent.trim()
  } else {
    // 普通文本内容
    singleColumnContent.value = content
  }
}

const handleDialogClose = () => {
  dialogVisible.value = false
  dialogTableData.value = []
  dialogColumns.value = []
}

const handleSingleColumnDialogClose = () => {
  singleColumnDialogVisible.value = false
  singleColumnContent.value = ''
  exceptionDetailList.value = []
}

const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  // 重置查询参数，但保留当前标签的状态
  const currentStatus = queryParams.status

  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    fixmedinsCode: null,
    systemId: null,
    risStudyId: null,
    status: currentStatus, // 保持当前状态
    source: null  // 清除上报节点过滤
  })
  getList()
}

// 生命周期
onMounted(() => {
  // 初始化时根据默认标签设置参数
  updateQueryParamsByTab(activeTab.value)
  getList()
})
</script>

<style scoped>
.api-field-cell {
  cursor: pointer;
  padding: 8px 0;
}

.api-field-cell:hover {
  background-color: var(--el-color-primary-light-9);
}

.abnormal-icon {
  color: var(--el-color-danger);
  margin-right: 4px;
}

.abnormal-text {
  color: var(--el-color-danger);
  font-weight: bold;
}

.normal-text {
  color: var(--el-color-success);
}

/* 单列弹窗内容的样式 */
.single-column-dialog-content {
  padding: 10px;
}

.single-column-content {
  white-space: pre-wrap;
  word-break: break-all;
  font-family: monospace;
  line-height: 1.5;
  max-height: 60vh;
  overflow-y: auto;
  padding: 15px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 4px;
  border: 1px solid var(--el-border-color);
  font-size: 14px;
}

/* 异常分组弹窗美化 */
.exception-group {
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f8fa;
  border-radius: 6px;
  border: 1px solid #eee;
}
.group-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 8px;
  color: var(--el-color-primary);
}
.group-msg {
  margin-bottom: 8px;
}
.msg-line {
  color: var(--el-color-danger);
  margin-bottom: 4px;
  font-size: 15px;
}
.group-time {
  color: #888;
  font-size: 13px;
}

/* 弹窗宽度优化 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>